//
//  PPLoginViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "PPLoginViewController.h"
#import "RegisterViewController.h"
#import "ForgotPSWViewController.h"

//#import "TTNeteaseIMManager.h"


@interface PPLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *pswTF;

@property (weak, nonatomic) IBOutlet UILabel *forgotPSWLab;
@property (weak, nonatomic) IBOutlet UIButton *showOrHideBtn;

@property (weak, nonatomic) IBOutlet UIButton *savePassword;
@property (assign, nonatomic) BOOL isSave;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation PPLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self initSaveData];
}

- (void)initSaveData {
    
    self.isSave = [TTUserModel sharedObject].isSaveAccountAndPassword;

    if ([TTUserModel sharedObject].isSaveAccountAndPassword) {
        self.phoneNumTF.text = [TTUserModel sharedObject].userLoginAccount;
        self.pswTF.text = [TTUserModel sharedObject].userLoginPSW;
        [self.savePassword setImage:[UIImage imageNamed:@"admire_bg"] forState:UIControlStateNormal];
    } else {
        self.phoneNumTF.text = @"";
        self.pswTF.text = @"";
        [self.savePassword setImage:[UIImage imageNamed:@"empty_bg"] forState:UIControlStateNormal];
    }
}

- (void)initView {
    
    self.title = @"登录";
        
    self.forgotPSWLab.userInteractionEnabled = YES;
    [self.forgotPSWLab addGestureTapTarget:self action:@selector(forgetPSW)];
    
    self.phoneNumTF.delegate = self;
    self.pswTF.delegate = self;
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    registBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    registBtn.frame = CGRectMake(0, 0, 60, 40);
    [registBtn sizeToFit];
    [registBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registUser) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:registBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    cancleBtn.frame = CGRectMake(0, 0, 60, 40);
    [cancleBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(cancleLogin) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:cancleBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)cancleLogin {
    
    if (self.completion) {
        self.completion(NO, @{});
    }
    
    [PPTabBarController setCurrentIndex:PPTabbarIndexTypeHome];
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    //存入，让viewwillappear不要弹出登录

}

- (void)registUser {
    
    [self.navigationController pushViewController:[RegisterViewController new] animated:YES];
}

- (void)forgetPSW {
    
    [self.navigationController pushViewController:[ForgotPSWViewController new] animated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.phoneNumTF) {
        // 这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {

            return YES;
            
        }  else if (self.phoneNumTF.text.length >= 11) {
            
            self.phoneNumTF.text = [textField.text substringToIndex:11];
            
            [SVProgressHUD showInfoWithStatus:@"手机号为11为数字"];
            [SVProgressHUD dismissWithDelay:0.5];
            
            [self.pswTF becomeFirstResponder];
            
            return NO;
        }
    }
    
    if (textField == self.pswTF) {
        NSString*toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if(textField ==self.pswTF && textField.isSecureTextEntry) {
            
            textField.text= toBeString;
            return NO;
        }
    }
    
    return YES;
}


- (IBAction)showOrHide:(id)sender {
    
    if (self.pswTF.isSecureTextEntry) {
        self.pswTF.secureTextEntry = NO;
        [self.showOrHideBtn setImage:[UIImage imageNamed:@"unhide_icon"] forState:UIControlStateNormal];
    } else {
        self.pswTF.secureTextEntry = YES;
        [self.showOrHideBtn setImage:[UIImage imageNamed:@"hide_icon"] forState:UIControlStateNormal];
    }
    
}

- (IBAction)savePasswordClicked:(id)sender {
    
    self.isSave = !self.isSave;
    [self.savePassword setImage:[UIImage imageNamed:self.isSave?@"admire_bg":@"empty_bg"] forState:UIControlStateNormal];
    //存储密码
}

- (IBAction)loginAction:(id)sender {
    
    if (!self.phoneNumTF.text.length) {
        [self alert:@"请输入手机号"];
        
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        [SVProgressHUD dismissWithDelay:1];
    } else {
        if (!self.pswTF.text.length) {

            [SVProgressHUD showErrorWithStatus:@"请输入密码"];
            [SVProgressHUD dismissWithDelay:1];

        } else {
            [self request_Login];
        }
    }
}

- (void)request_Login {
    self.loginBtn.userInteractionEnabled = NO;
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.phoneNumTF.text forKey:@"phone"];
    [dic setValue:self.pswTF.text forKey:@"password"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_LOGIN_API];
    
    WEAKSELF
    
    [SVProgressHUD showWithStatus:@"正在登陆"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        self.loginBtn.userInteractionEnabled = YES;
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            NSDictionary *resultDic = [data valueForKey:@"data"];
            if ([code isEqualToString:@"200"]) {
                
                [[TTUserModel sharedObject].userModelDefault setValue:@"loged" forKey:@"login_status"];
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"phone"] forKey:@"PP_user_account"];
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"avatar"] forKey:@"user_icon"];
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"username"] forKey:@"uer_name"];
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"token"] forKey:@"access_token"];
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"referralCode"] forKey:@"user_recommandCode"];
                
                [[TTUserModel sharedObject].userModelDefault setValue:[resultDic valueForKey:@"id"] forKey:@"uer_id"];

                
                if (self.isSave) {
                    //登录成功后保存密码
                    [[TTUserModel sharedObject].userModelDefault setValue:self.phoneNumTF.text forKey:@"PP_user_account"];
                    [[TTUserModel sharedObject].userModelDefault setValue:self.pswTF.text forKey:@"PP_user_password"];
                    [[TTUserModel sharedObject].userModelDefault setValue:@"1" forKey:@"PP_issaveaccount"];
                } else {
                    //登录成功后保存密码
                    [[TTUserModel sharedObject].userModelDefault setValue:@"" forKey:@"PP_user_account"];
                    [[TTUserModel sharedObject].userModelDefault setValue:@"" forKey:@"PP_user_password"];
                    [[TTUserModel sharedObject].userModelDefault setValue:@"0" forKey:@"PP_issaveaccount"];
                }
                [[TTUserModel sharedObject].userModelDefault synchronize];
                
                if (self.completion) {
                    self.completion(YES, data);
                }
                
                [weakSelf.view endEditing:YES];
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:0.5];
            }
            
        } else {
            
            [SVProgressHUD showErrorWithStatus:@"返回为空"];
        }
        
        
    } FailedBlock:^(NSError * _Nonnull error) {
        self.loginBtn.userInteractionEnabled = YES;
        
        NSString *msg = @"请求异常";
        switch (error.code) {
            case kCFURLErrorUnknown:{
                msg = @"未知错误";
            } break;
            case kCFURLErrorCancelled:{
                msg = @"错误取消";
            } break;
            case kCFURLErrorBadURL:{
                msg = @"错误的URL";
            } break;
            case kCFURLErrorTimedOut:{
                msg = @"请求超时";
            } break;
            case kCFURLErrorUnsupportedURL:{
                msg = @"不支持的URL";
            } break;
            case kCFURLErrorCannotFindHost:{
                msg = @"无法找到主机";
            } break;
            case kCFURLErrorCannotConnectToHost:{
                msg = @"无法连接到主机";
            } break;
            case kCFURLErrorNetworkConnectionLost:{
                msg = @"网络连接丢失";
            } break;
            case kCFURLErrorDNSLookupFailed:{
                msg = @"DNS查找失败";
            } break;
            case kCFURLErrorHTTPTooManyRedirects:{
                msg = @"HTTP重定向太多";
            } break;
            case kCFURLErrorResourceUnavailable:{
                msg = @"错误的资源不可用";
            } break;
            case kCFURLErrorNotConnectedToInternet:{
                msg = @"未连接互联网";
            } break;
            case kCFURLErrorRedirectToNonExistentLocation:{
                msg = @"重定向到不存在的位置";
            } break;
            case kCFURLErrorBadServerResponse:{
                msg = @"坏的服务器响应";
            } break;
                
            default:
                break;
        }

        [SVProgressHUD showErrorWithStatus:msg];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}

@end
